package plugins

import SYSTEM_CONFG
import listModifyFile
import org.apache.commons.io.FileUtils
import java.io.File
import java.io.FileInputStream
import java.util.*

val USER_HOME = System.getProperties()["user.home"] as String

interface Plugin{
    fun install()

    fun exec()

    fun uninstall()
}

data class SystemCfgPluginCtx(val syncfp: String)

class SystemCfgPlugin : Plugin {
    val nfp = SYSTEM_CONFG.base + File.separator + "extras" + File.separator + "systemcfg"
    override fun install() {
        println("SystemCfgPlugin is started")
        FileUtils.forceMkdir(File(nfp))
    }

    fun loadCfg(fp: String ="./systemcfg.plugin") {
        val props = Properties()
        FileInputStream(fp).use {
            props.load(it)
        }
    }

    override fun exec() {
        println("同步本地系统文件")
        val listenerDir = File(USER_HOME)
        if (listenerDir.exists()) {
            val mmds = listenerDir.listFiles()
                ?.filter { it.isFile }
            mmds?.apply {
                val mds = this
                val changeFile = listModifyFile(nfp, mds)
                changeFile.add?.forEach {
                    val name = it.name
                    FileUtils.copyFile(it, File(nfp, name))
                }
                changeFile.update?.forEach {
                    val name = it.name
                    FileUtils.copyFile(it, File(nfp, name))
                    FileUtils.forceMkdir(File("$nfp/update/${System.currentTimeMillis()}"))
                    FileUtils.copyFile(File(nfp, name), File("$nfp/update/${System.currentTimeMillis()}/$name"))
                }
                changeFile.delete?.forEach {
                    val name = it.name
                    FileUtils.forceMkdir(File("$nfp/delete/${System.currentTimeMillis()}"))
                    FileUtils.copyFile(File(nfp, name), File("$nfp/delete/${System.currentTimeMillis()}/$name"))
                }
            }
            keepLastModify(100, "$nfp/update")
            keepLastModify(100, "$nfp/delete")
        }
    }

    fun keepLastModify(topN: Int, fp: String) {
        val listenDir = File(fp)
        if (listenDir.isDirectory && listenDir.exists()) {
            val innerFiles = listenDir.listFiles()
            innerFiles?.sortByDescending { it.lastModified() }
            innerFiles?.forEachIndexed { index, file ->
                if (index > topN) {
                    file.delete()
                }
            }
        }
    }

    override fun uninstall() {
        println("SystemCfgPlugin uninstall")
    }

}